package com.meisiabc.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 *
 */
public class JwtUtil {

    private static final String MAC_INSTANCE_NAME = "HMacSHA256";
    private static final String API_SECRET = "xGIXB3aJc3qIie9m8mCG203TwYYmuC27YLmP";
    public static final String API_KEY = "yZDF6uRpQbmkmAuzbdE7Yg";


    public static String Hmacsha256(String secret, String message)
        throws NoSuchAlgorithmException, InvalidKeyException {
        Mac hmac_sha256 = Mac.getInstance(MAC_INSTANCE_NAME);
        SecretKeySpec key = new SecretKeySpec(secret.getBytes(), MAC_INSTANCE_NAME);
        hmac_sha256.init(key);
        byte[] buff = hmac_sha256.doFinal(message.getBytes());
        return Base64.encodeBase64URLSafeString(buff);
    }

    public static String genJWTToken() throws InvalidKeyException, NoSuchAlgorithmException {
        long time = DateUtil.addDay(new Date(), 1).getTime();
        String header = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
        String claim = "{\"iss\":\"" + API_KEY + "\", \"exp\":" + time + "}";
        String base64Header = Base64.encodeBase64URLSafeString(header.getBytes());
        String base64Claim = Base64.encodeBase64URLSafeString(claim.getBytes());
        String signature = Hmacsha256(API_SECRET, base64Header + "." + base64Claim);
        String jwt = base64Header + "." + base64Claim + "." + signature;
        return jwt;
    }
}